package com.duck.user.websocket;

import com.duck.user.utils.JwtTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;

@Slf4j
@Component
public class JwtHandshakeConfig extends ServerEndpointConfig.Configurator implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        JwtHandshakeConfig.applicationContext = applicationContext;
    }

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        // 允许跨域
        response.getHeaders().put("Access-Control-Allow-Origin", Collections.singletonList("*"));

        // 从 URL 查询参数中获取 token
        String query = request.getRequestURI().getQuery();
        String token = null;

        if (query != null) {
            String[] pairs = query.split("&");
            for (String pair : pairs) {
                int idx = pair.indexOf("=");
                if (idx > 0) {
                    String key = URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8);
                    if ("token".equals(key)) {
                        token = URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8);
                        break;
                    }
                }
            }
        }

        if (token != null && !token.isEmpty()) {
            try {
                JwtTool jwtTool = applicationContext.getBean(JwtTool.class);
                String userId = String.valueOf(jwtTool.parseToken(token));
                sec.getUserProperties().put("userId", userId);
            } catch (Exception e) {
                log.error("JWT 解析失败", e);
            }
        }
    }
}